#include <windows.h>
#include <stdarg.h>
#include <stdio.h>
#include <time.h>

#include "io_console.h"


#define CONSOLE_PATH "console.txt"

bool consoleOpen = false;

void outputStr(char * str)
{
	if (!consoleOpen)
		resetConsole();
	FILE *f = fopen(CONSOLE_PATH,"at");
	if (!f) return;

	time_t rawtime;
	struct tm * timeinfo;
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	char buffer [128];

	strftime (buffer,128,"%d/%m/%Y %H:%M:%S",timeinfo);

	fprintf(f,"[%s]  %s\n",buffer,str);
	fclose(f);
}

void resetConsole()
{
	FILE *f=fopen(CONSOLE_PATH,"wt");
	fclose(f);
	consoleOpen = true;

	outputStr("Console started");
}

void writeConsole(char *format, ...)
{
	va_list ap;
	char msg[2048];

	va_start(ap,format);
	vsprintf(msg,format,ap);
	va_end(ap);
	outputStr(msg);
}

void errorConsole(int level,char *format, ...)
{
	va_list ap;
	char msg[2048];

	va_start(ap,format);
	vsprintf(msg,format,ap);
	va_end(ap);
	outputStr(msg);

	if (level == CONSOLE_FATAL)
	{
		MessageBox(NULL, msg, "ERROR", MB_OK|MB_ICONERROR);	
		exit(0);
	}
}
